﻿using System;
using System.Collections.Generic;
using System.Text;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Math;
namespace Xeno.Core
{
    public class XenoMaterial
    {
        public static Dictionary<string, XenoMaterial> MatMap = new Dictionary<string, XenoMaterial>();
        public string Name { get; set; }
        public XenoTexture DiffuseMap { get; set; }
        public XenoTexture NormalMap { get; set; }
        public XenoTexture HeightMap { get; set; }
        public XenoTexture GlowMap { get; set; }

        public Vector4 DiffuseColor { get; set; }
        public Vector4 SpecularColor { get; set; }
        public float SpecularPower { get; set; }

        public XenoEffect Effect { get; set; }
        public bool AutoEffectParameters { get; set; }
        public XenoMaterial(string name)
        {
            Name = name;
            MatMap.Add(name, this);
            ResetMaterial();
        }
        public void ResetMaterial()
        {
            
            DiffuseMap = NormalMap = HeightMap = GlowMap = null;
            Effect = new XenoEffect("Content/Shader/XenoMaterial_DirLight.vertex", "Content/Shader/XenoMaterial_DirLight.fragment");
            AutoEffectParameters = true;
            DiffuseColor = new Vector4(1, 1, 1, 1);
            SpecularColor = new Vector4(1, 1, 1, 1);
            SpecularPower = 0.0f;

        }
        /// <summary>
        /// The base XenoEffect class is set up automagically by the engine. Use it wisely, luke.
        /// </summary>
        public void Bind()
        {

            if (DiffuseMap != null) DiffuseMap.Bind(0);

            XenoDebug.AssertNull(Effect, "XenoMaterial.Bind");

            Effect.Use();

            if (AutoEffectParameters)
            {
                if (XenoCore.CurrentLight != null)
                {
                    
                    Effect.SetVec3("LightDirection", XenoCore.CurrentLight.Light.Direction);
                    Effect.SetVec3("LightPosition", XenoCore.CurrentLight.LocalPosition);
                    Effect.SetColor("LightDiffuseColor", XenoCore.CurrentLight.Light.DiffuseColor);
                    Effect.SetColor("LightAmbientColor", XenoCore.CurrentLight.Light.AmbientColor);

                }
                Effect.SetVec4("MaterialDiffuseColor", DiffuseColor);
                Effect.SetVec4("MaterialSpecularColor", SpecularColor);
                Effect.SetFloat("MaterialSpecularPower", SpecularPower);
                Effect.SetVec3("ViewDirection", XenoCore.CurrentView.Direction);
                Effect.SetInt("MaterialDiffuseMap", 0);
      
            }
            
            

        }
        public void Unbind()
        {
            XenoDebug.AssertNull(Effect, "XenoMaterial.Unbind");
            Effect.Fin();

            if (DiffuseMap != null) DiffuseMap.Unbind(0);

        }
    }
}
